package com.sywb.chuangyebao.contract;

import android.text.TextUtils;
import android.view.SurfaceView;
import android.widget.ProgressBar;

import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.video.PublishVideoPlayer;
import com.tencent.ugcupload.TXUGCPublish;
import com.tencent.ugcupload.TXUGCPublishTypeDef;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.SharedUtils;

/**
 * Created by duxl on 2018/5/24.
 */

public interface PublishVideoEditContract {

    interface View extends IView {
        SurfaceView getSurfaceView();
        /** 视频本地文件路径 */
        String getVideoSource();
        /** 视频播放秒数 */
        int getVideoDuration();
        String getVideoDesc();
        ProgressBar getProgressBar();
        void onPlayCompleted();
        void showPublishSuccessDialog();
        int getSourceType();
        String getVideoId();
    }

    class Presenter extends BasePresenter<View> implements PublishVideoPlayer.OnProgressChangeListner, IAliyunVodPlayer.OnPreparedListener {

        PublishVideoPlayer mVideoPlayer;
        String mVideoId; // 腾讯云视频id（上传到腾讯云后的值）
        String mVideoUrl; // 腾讯云视频url（上传到腾讯云后的值）

        @Override
        public void onStart() {
            mVideoPlayer = new PublishVideoPlayer(mContext, mView.getSurfaceView());
            mVideoPlayer.setOnProgressChangeListner(this);
            mVideoPlayer.setOnPreparedListener(this);
            mVideoPlayer.setSurfaceView(mView.getSurfaceView());
            mVideoPlayer.setSource(mView.getVideoSource());
            mView.getProgressBar().setVisibility(android.view.View.VISIBLE);
            play();
        }

        @Override
        public void onProgressChanged(int current, int total) {
            if(mView == null) {
                return;
            }

            if(mVideoPlayer.getPlayerState() == IAliyunVodPlayer.PlayerState.Completed) {
                mView.onPlayCompleted();
            }
        }

        @Override
        public void onPrepared() {
            mView.getSurfaceView().setEnabled(true);
            mView.getProgressBar().setVisibility(android.view.View.GONE);
//            mView.getSeekBar().setEnabled(true);
        }

        public void play() {
            try {
                mVideoPlayer.play();
            }catch (Exception e) {
                Logger.e(e.getMessage());
                mView.showMessage(e.getMessage());
            }
        }

        public void pause() {
            mVideoPlayer.pause();
        }

        public boolean isPlaying() {
            return mVideoPlayer.getPlayerState() == IAliyunVodPlayer.PlayerState.Started;
        }

        /** 发布视频 */
        public void publish() {
            if(mView.getSourceType() == 2) { // 从我的视频列表过来修改视频
                edit();
            } else {
                if (!TextUtils.isEmpty(mVideoId) && !TextUtils.isEmpty(mVideoUrl)) { // 视频已经上传到腾讯云
                    save(mVideoId, mVideoUrl);
                } else { // 获取腾讯上传签名后再上传
                    getVideoSignature();
                }
            }
        }

        private void getVideoSignature() {
            mView.showProgress();
            HttpUtils.getVideoSignature(new HttpCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    Logger.i("腾讯云上传签名: " + s);
                    uploadVideoToTencent(s);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    mView.hideProgress();
                    mView.showMessage(strMsg);
                }
            });
        }

        /**
         * 上传视频到腾讯云服务
         * @param signature
         */
        private void uploadVideoToTencent(String signature) {
            // 初始化一个上传对象
            String openId = SharedUtils.getString(Constants.USEROPENID, "");
            TXUGCPublish mVideoPublish = new TXUGCPublish(mActivity.getApplicationContext(), openId);

            // 设置上传对象的回调
            mVideoPublish.setListener(new TXUGCPublishTypeDef.ITXVideoPublishListener() {
                @Override
                public void onPublishProgress(long uploadBytes, long totalBytes) {
                    //mProgress.setProgress((int) (100*uploadBytes/totalBytes));
                    Logger.i("上传视频到腾讯云进度：" + uploadBytes + "/" + totalBytes);
                }

                @Override
                public void onPublishComplete(final TXUGCPublishTypeDef.TXPublishResult result) {
                    Logger.i("上传视频到腾讯云返回："+result.retCode + " Msg:" + (result.retCode == 0 ? result.videoURL : result.descMsg));
                    mView.hideProgress();
                    if(result.retCode != 0) {
                        String msg = String.format(mActivity.getString(R.string.upload_video_fail) + "(%d)", result.retCode);
                        mView.showMessage(msg);
                    } else {
                        mVideoId = result.videoId;
                        mVideoUrl = result.videoURL;
                        save(mVideoId, mVideoUrl);
                    }
                }
            });

            // 构造上传参数
            TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
            param.signature = signature;
            param.videoPath = mView.getVideoSource();

            // 调用上传
            int publishCode = mVideoPublish.publishVideo(param);
            Logger.i("上传视频到腾讯云：publishCode=" + publishCode);
            if(publishCode != 0) {
                mView.hideProgress();
                String msg = String.format(mActivity.getString(R.string.upload_video_fail) + "(%d)", publishCode);
                mView.showMessage(msg);
            }
        }

        /**
         * 保存
         */
        private void save(String mediaId, String mediaUrl) {
            mView.showProgress();
            HttpUtils.publishVideo(mView.getVideoDesc(), mediaId, mediaUrl, mView.getVideoDuration(), new HttpCallback<Object>() {
                @Override
                public void onSuccess(Object o) {
                    RxBus.get().post(Constants.POST_VIDEO_SAVE, "");
                    mView.showPublishSuccessDialog();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    mView.showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    mView.hideProgress();
                }
            });
        }

        /**
         * 编辑
         */
        private void edit() {
            mView.showProgress();
            HttpUtils.editVideo(mView.getVideoId(), mView.getVideoDesc(), new HttpCallback<Object>() {
                @Override
                public void onSuccess(Object o) {
                    mView.showPublishSuccessDialog();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    mView.showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    mView.hideProgress();
                }
            });
        }
    }
}
